package com.strato.passport.client.v1_0_0.validate;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;

import com.strato.annotation.osgi.v1_0_0.service.OsgiService;
import com.strato.base.env.v1_0_0.GlobalEnvironment;
import com.strato.passport.client.v1_0_0.http.HttpClientFactory;
import com.strato.passport.client.v1_0_0.http.TicketValidator;

import net.sf.json.JSONObject;

@OsgiService
public class PassportValidatorImpl implements TicketValidator {

	@SuppressWarnings("unchecked")
	@Override
	public Map<Object, Object> validate(String ticket) {
		CloseableHttpClient httpclient = HttpClientFactory.getHttpClient();
		try{
			String passportHome=GlobalEnvironment.getInstance().resolveString("${passport.home}");
			HttpGet get=new HttpGet(passportHome+"/validate/"+ticket);
			CloseableHttpResponse response = httpclient.execute(get);
			int state = response.getStatusLine().getStatusCode();
			if(state>=200&&state<300){
				InputStream is = response.getEntity().getContent();
				String encoding = "UTF-8";
				String json=IOUtils.toString(is, encoding);
				if(json==null||"".equals(json)){
					return null;
				}
				JSONObject user = JSONObject.fromObject(json);
				return user;
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

}
